﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace XKPlatform.Common
{
    public class ClientHelper
    {
        /// <summary>
        /// 发送请求 Post
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="HttpUrl"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public T SendRequestPost<T>(string HttpUrl, Dictionary<string, string> param)
        {

            string json = SendRequestPost(HttpUrl, param);
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 发送请求 Post
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="HttpUrl"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string SendRequestPost(string HttpUrl, Dictionary<string, string> param)
        {
            HttpClient _HttpClient = new HttpClient();
            _HttpClient.BaseAddress = new Uri(HttpUrl);

            _HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _HttpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));

            var respon = _HttpClient.PostAsync(HttpUrl, new FormUrlEncodedContent(param));

            return respon.Result.Content.ReadAsStringAsync().Result;
        }

        /// <summary>
        /// 发送请求 Post
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="HttpUrl"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string SendRequestPost<T>(string HttpUrl, T param)
        {
            var requestJson = JsonConvert.SerializeObject(param);
            HttpContent httpContent = new StringContent(requestJson);

            HttpClient _HttpClient = new HttpClient();
            _HttpClient.BaseAddress = new Uri(HttpUrl);
            _HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _HttpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));

            var respon = _HttpClient.PostAsync(HttpUrl, httpContent);
            return respon.Result.Content.ReadAsStringAsync().Result;
        }
          
        /// <summary>
        /// 发送请求 Get
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="HttpUrl"></param>
        /// <returns></returns>
        public T SendRequestGet<T>(string HttpUrl)
        {
            HttpClient _HttpClient = new HttpClient();
            _HttpClient.BaseAddress = new Uri(HttpUrl);
            _HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _HttpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));

            var respon = _HttpClient.GetAsync(HttpUrl);

            string json = respon.Result.Content.ReadAsStringAsync().Result;
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postStr"></param>
        public string HttpPostAsync(string HttpUrl, string param)
        {
            var webClient = new WebClient { Encoding = Encoding.UTF8 };
            webClient.Headers.Add("Content-Type", "application/json;charset=utf-8");
            string json = webClient.UploadString(HttpUrl, "POST", param);
            return json;
        }

        public T HttpPostAsync<T>(string HttpUrl, string param)
        {
            string json = HttpPostAsync(HttpUrl, param);
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// get请求--通过代理发送请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postStr"></param>
        public string HttpGetAsyncByProxy(string HttpUrl)
        {
            var webClient = new WebClient { Encoding = Encoding.UTF8 };
            //WebProxy WP = SetProxy();
            //webClient.Proxy = WP;//将代理赋值给HttpWebRequest的Proxy属性    
            webClient.Headers.Add("Content-Type", "application/json;charset=utf-8");

            string json = webClient.DownloadString(HttpUrl);
            return json;
        }

        /// <summary>
        /// get请求--通过代理发送请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="HttpUrl"></param>
        /// <returns></returns>
        public T HttpGetAsyncByProxy<T>(string HttpUrl)
        {
            string json = HttpGetAsyncByProxy(HttpUrl);
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// post请求--通过代理发送请求
        /// </summary>
        /// <param name="HttpUrl"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string HttpPostAsyncByProxy<T>(string HttpUrl, T param)
        {
            var requestJson = JsonConvert.SerializeObject(param);
            var webClient = new WebClient { Encoding = Encoding.UTF8 };
            //WebProxy WP = SetProxy();
            //webClient.Proxy = WP;//将代理赋值给HttpWebRequest的Proxy属性   
            webClient.Headers.Add("Content-Type", "application/json;charset=utf-8");

            string json = webClient.UploadString(HttpUrl, "POST", requestJson);
            return json;
        }

        /// <summary>
        /// post请求--通过代理发送请求
        /// </summary>
        /// <param name="HttpUrl"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string HttpPostAsyncByProxy(string HttpUrl, string param)
        {
            byte[] postData = Encoding.UTF8.GetBytes(param);
            WebClient webClient = new WebClient();
            //WebProxy WP = SetProxy();
            //webClient.Proxy = WP;//将代理赋值给HttpWebRequest的Proxy属性   
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可  
            byte[] responseData = webClient.UploadData(HttpUrl, "POST", postData);//得到返回字符流  
            string srcString = Encoding.UTF8.GetString(responseData);//解码  

            return srcString;
        }

        ///// <summary>
        ///// 设置代理
        ///// </summary>
        ///// <returns></returns>
        //public WebProxy SetProxy()
        //{
        //    WebProxy WP;
        //    //int ProxyPort = int.Parse(HttpContextCore.Configuration["ProxyInfo:ProxyPort"]);
        //    //string ProxyIP = HttpContextCore.Configuration["ProxyInfo:ProxyIP"];
        //    //WP = new WebProxy(ProxyIP, ProxyPort);
        //    ICredentials jxCredt = new NetworkCredential();
        //    WP.Credentials = jxCredt;

        //    return WP;
        //}

        /// <summary>
        /// 请求https地址路径
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string HttpsPostUserInfo(string url)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
                request.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;

            }
            else
            {
                request = (HttpWebRequest)WebRequest.Create(url);
            }
            request.Method = "POST";    //使用POST方式发送数据
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = null;
            request.AllowAutoRedirect = true;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.Accept = "*/*";


            byte[] data = Encoding.UTF8.GetBytes("json");
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            //获取网页响应结果
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string result = string.Empty;
            using (StreamReader sr = new StreamReader(stream))
            {
                result = sr.ReadToEnd();
            }
            return result;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

    }
}
